﻿using Able.Common.DEncrypt;
using Api.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Api.Web.helper
{
    public class CookieHelper
    {
        public static void SetCookie(string name, string value, bool isHttpOnly = false)
        {
            HttpCookie cookie = new HttpCookie(name);
            cookie.Value = HttpContext.Current.Server.UrlEncode(value);

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static string GetCookie(string name)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(name);

            if (cookie != null)
            {
                return HttpContext.Current.Server.UrlDecode(cookie.Value);
            }
            return "";
        }

        public static void RemoveCookie(string name)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(name);

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 设置网站用户登录时的cookie
        /// </summary>
        /// <param name="memberId"></param>
        public static void SetLoginCookie(User user)
        {
            var str = DESEncrypt.Encrypt(user.Id.ToString());
            SetCookie(CookieName.UserId, str);
        }

        public static void RemoveLoginCookie()
        {
            RemoveCookie(CookieName.UserId);
        }
    }

    /// <summary>
    /// class 引用类型，struct是值类型
    /// struct不支持继承，
    /// </summary>
    public class CookieName
    {
        /// <summary>
        /// Member_xxx
        /// </summary>
        public static string UserId => "uuid";

        public static string ProjectId => "ppid";
    }
}
